import 'dart:convert';
import 'package:flutter/foundation.dart';
import '../services/data_persistence_manager.dart';
import '../models/user_model.dart';

/// 全局状态协调器
class GlobalStateCoordinator extends ChangeNotifier {
  final DataPersistenceManager _dataPersistenceManager;

  // 用户相关状态
  UserModel? _currentUser;
  List<UserModel> _defaultUsers = [];

  GlobalStateCoordinator(this._dataPersistenceManager) {
    _initializeDefaultUsers();
    _loadAppState();
    _ensureDefaultUsersInStorage();
  }

  bool get isLoggedIn => _currentUser != null;
  UserModel? get currentUser => _currentUser;
  List<UserModel> get defaultUsers => List.unmodifiable(_defaultUsers);

  /// 加载应用状态
  Future<void> _loadAppState() async {
    try {
      final isLoggedIn = _dataPersistenceManager.getBool('isLoggedIn') ?? false;
      if (isLoggedIn) {
        final userJsonString = _dataPersistenceManager.getString('currentUser');
        if (userJsonString != null && userJsonString.isNotEmpty) {
          try {
            final userMap = jsonDecode(userJsonString) as Map<String, dynamic>;
            _currentUser = UserModel.fromJson(userMap);
          } catch (e) {
            debugPrint('解析用户数据失败: $e');
            await _dataPersistenceManager.remove('currentUser');
            await _dataPersistenceManager.setBool('isLoggedIn', false);
          }
        }
      }
    } catch (e) {
      debugPrint('加载应用状态失败: $e');
    }
  }

  /// 用户注册
  Future<bool> register(
    String account,
    String password, {
    String userName = '',
    String avatar = '',
  }) async {
    try {
      // 检查账号是否已存在
      final existingUsers =
          _dataPersistenceManager.getStringList('registeredUsers') ?? [];
      for (String userJson in existingUsers) {
        final userMap = jsonDecode(userJson) as Map<String, dynamic>;
        if (userMap['account'] == account) {
          return false; // 账号已存在
        }
      }

      // 创建新用户
      final newUser = UserModel(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        account: account,
        password: password,
        userName: userName.isEmpty ? account : userName,
        avatar: avatar,
      );

      // 保存到注册用户列表
      existingUsers.add(jsonEncode(newUser.toJson()));
      await _dataPersistenceManager.setStringList(
        'registeredUsers',
        existingUsers,
      );

      return true; // 注册成功
    } catch (e) {
      debugPrint('用户注册失败: $e');
      return false;
    }
  }

  /// 用户登录
  Future<bool> login(String account, String password) async {
    try {
      // 从注册用户列表中查找匹配的用户
      final existingUsers =
          _dataPersistenceManager.getStringList('registeredUsers') ?? [];
      for (String userJson in existingUsers) {
        final userMap = jsonDecode(userJson) as Map<String, dynamic>;
        final user = UserModel.fromJson(userMap);

        if (user.account == account && user.password == password) {
          // 登录成功，设置当前用户
          _currentUser = user;

          // 保存登录状态
          await _dataPersistenceManager.setString(
            'currentUser',
            jsonEncode(_currentUser!.toJson()),
          );
          await _dataPersistenceManager.setBool('isLoggedIn', true);

          notifyListeners();
          return true; // 登录成功
        }
      }

      return false; // 账号或密码错误
    } catch (e) {
      debugPrint('用户登录失败: $e');
      return false;
    }
  }

  /// 用户登出
  Future<void> logout() async {
    _currentUser = null;

    await _dataPersistenceManager.setBool('isLoggedIn', false);
    await _dataPersistenceManager.remove('currentUser');

    notifyListeners();
  }

  /// 更新用户信息
  Future<void> updateUserInfo(String userName, {String? avatar}) async {
    if (_currentUser != null) {
      _currentUser = UserModel(
        id: _currentUser!.id,
        account: _currentUser!.account,
        password: _currentUser!.password,
        userName: userName,
        avatar: avatar ?? _currentUser!.avatar,
      );

      // 保存更新后的用户数据
      await _dataPersistenceManager.setString(
        'currentUser',
        jsonEncode(_currentUser!.toJson()),
      );
      notifyListeners();
    }
  }

  /// 清除所有数据
  Future<void> clearAllData() async {
    await _dataPersistenceManager.clear();
    _currentUser = null;
    notifyListeners();
  }

  /// 初始化默认用户数据
  void _initializeDefaultUsers() {
    _defaultUsers = [
      UserModel(
        id: 'default_user_001',
        account: 'admin',
        password: '123456',
        userName: 'Cecilia',
        avatar: 'assets/images/avatar1.png',
      ),
      UserModel(
        id: 'default_user_002',
        account: 'music_teacher_pro',
        password: 'demo123',
        userName: 'Michael',
        avatar: 'assets/images/avatar2.png',
      ),
      UserModel(
        id: 'default_user_003',
        account: 'rock_fan_2023',
        password: 'demo123',
        userName: 'Lily',
        avatar: 'assets/images/avatar3.png',
      ),
      UserModel(
        id: 'default_user_004',
        account: 'electric_newbie',
        password: 'demo123',
        userName: 'Newbie',
        avatar: 'assets/images/avatar4.png',
      ),
      UserModel(
        id: 'default_user_005',
        account: 'piano_master',
        password: 'demo123',
        userName: 'Master',
        avatar: 'assets/images/avatar5.png',
      ),
      UserModel(
        id: 'default_user_006',
        account: 'drum_enthusiast',
        password: 'demo123',
        userName: 'Johnson',
        avatar: 'assets/images/avatar6.png',
      ),
    ];
  }

  /// 根据用户ID获取默认用户
  UserModel? getDefaultUserById(String userId) {
    try {
      return _defaultUsers.firstWhere((user) => user.id == userId);
    } catch (e) {
      return null;
    }
  }

  /// 获取随机默认用户
  UserModel getRandomDefaultUser() {
    if (_defaultUsers.isEmpty) return _getDefaultFallbackUser();
    final randomIndex = DateTime.now().millisecond % _defaultUsers.length;
    return _defaultUsers[randomIndex];
  }

  /// 获取默认后备用户（当默认用户列表为空时使用）
  UserModel _getDefaultFallbackUser() {
    return UserModel(
      id: 'fallback_user',
      account: 'anonymous_user',
      password: 'demo123',
      userName: 'Anonymous User',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=anonymous',
    );
  }

  /// 确保默认用户存储在registeredUsers中
  Future<void> _ensureDefaultUsersInStorage() async {
    try {
      final existingUsers =
          _dataPersistenceManager.getStringList('registeredUsers') ?? [];
      final existingUserIds = <String>{};

      // 获取已存在用户的ID
      for (String userJson in existingUsers) {
        try {
          final userMap = jsonDecode(userJson) as Map<String, dynamic>;
          existingUserIds.add(userMap['id'] as String);
        } catch (e) {
          debugPrint('解析已存在用户数据失败: $e');
        }
      }

      // 检查并添加缺失的默认用户
      bool hasNewUsers = false;
      final updatedUsers = List<String>.from(existingUsers);

      for (UserModel defaultUser in _defaultUsers) {
        if (!existingUserIds.contains(defaultUser.id)) {
          updatedUsers.add(jsonEncode(defaultUser.toJson()));
          hasNewUsers = true;
          debugPrint('添加默认用户到存储: ${defaultUser.userName}');
        }
      }

      // 如果有新用户，保存更新后的列表
      if (hasNewUsers) {
        await _dataPersistenceManager.setStringList(
          'registeredUsers',
          updatedUsers,
        );
        debugPrint('默认用户已添加到存储，总用户数: ${updatedUsers.length}');
      }
    } catch (e) {
      debugPrint('确保默认用户存储失败: $e');
    }
  }

  /// 获取所有注册用户（包括默认用户）
  List<UserModel> getAllRegisteredUsers() {
    try {
      final existingUsers =
          _dataPersistenceManager.getStringList('registeredUsers') ?? [];
      return existingUsers.map((userJson) {
        final userMap = jsonDecode(userJson) as Map<String, dynamic>;
        return UserModel.fromJson(userMap);
      }).toList();
    } catch (e) {
      debugPrint('获取注册用户失败: $e');
      return [];
    }
  }
}
